<?php
/**
 * Created by PhpStorm.
 * User: renshan
 * Date: 16-6-19
 * Time: 上午10:50
 */

namespace ApiBundle\Service;


use AccountBundle\Entity\Bill;
use AccountBundle\Entity\Category;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use UserBundle\Entity\User;

/**
 * Class UserService
 * @package ApiBundle\Service
 * 用户服务类
 */
class UserService
{
    protected $container;
    protected $request;
    private $user;
    private $category;

    /**
     * UserService constructor.
     * @param ContainerInterface $containerInterface
     */
    public function __construct(ContainerInterface $containerInterface, RequestStack $requestStack)
    {
        $this->container    = $containerInterface;
        $this->request      = $requestStack->getCurrentRequest();
    }

    /**
     * @return Registry
     */
    private function getDoctrine()
    {
        return $this->container->get('doctrine');
    }

    /**
     * @return User
     */
    public function getUser()
    {
        if($this->user == null) {
            $api_token = $this->container->get('api.token');
            return $this->getDoctrine()->getRepository('UserBundle:User')->loadUserByApiToken($api_token);
        }

        return $this->user;
    }

    public function getCategory()
    {
        if($this->category == null) {
            return $this->getDoctrine()->getRepository('AccountBundle:Category')->loadByUser($this->getUser());
        }

        return $this->category;
    }

    /**
     * @return array,null
     * 获得账单类型，即收入、支出
     */
    public function getTypes()
    {
        return $this->getDoctrine()->getRepository('AccountBundle:Type')->findAll();
    }

    /**
     * @param Category $category
     * @return Category
     * 用户添加一个分类
     */
    public function addCategory($name)
    {
        /**
         * @var Category
         */
        $exists = $this->getDoctrine()->getRepository('AccountBundle:Category')->createQueryBuilder('c')
                    ->where('c.user = :user and c.name = :name')
                    ->setParameter('user', $this->getUser())
                    ->setParameter('name', $name)
                    ->getQuery()
                    ->getOneOrNullResult();

        if($exists) {
            return null;
        }


        $category = new Category();
        $category->setName($name);
        $category->setUser($this->getUser());

        $em = $this->getDoctrine()->getManager();
        $em->persist($category);
        $em->flush();
        return $category;
    }

    public function updateCategory($name, $new_name)
    {
        /**
         * @var Category || null
         */
        $category = $this->getDoctrine()->getRepository('AccountBundle:Category')->createQueryBuilder('c')
            ->where('c.user = :user and c.name = :name')
            ->setParameter('user', $this->getUser())
            ->setParameter('name', $name)
            ->getQuery()
            ->getOneOrNullResult();

        if($category == null) {
            return null;
        }

        $category->setName($new_name);

        $em = $this->getDoctrine()->getManager();
        $em->persist($category);
        $em->flush($category);

        return $category;

    }

    /**
     * @return Bill|null
     * 用户记一笔账
     */
    public function addBill()
    {
        $price      =   $this->request->get('price');
        $what_for   =   $this->request->get('what_for');
        $time       =   $this->request->get('time') ? new \DateTime($this->request->get('time')) : new \DateTime('now');
        $location   =   $this->request->get('location');
        $address    =   $this->request->get('address');
        $type       =   $this->request->get('type');
        $category   =   $this->request->get('category');

        if($type == null || $category == null) {
            echo $type;
            return null;
        }

        $type       =   $this->getDoctrine()->getRepository('AccountBundle:Type')->find($type);
        $category   =   $this->getDoctrine()->getRepository('AccountBundle:Category')->find($category);

        if($type == null || $category == null) {
            return null;
        }

        $bill       =   new Bill();
        $bill->setAddress($address);
        $bill->setCategory($category);
        $bill->setLocation($location);
        $bill->setPrice($price);
        $bill->setTime($time);
        $bill->setType($type);
        $bill->setWhatFor($what_for);

        $em = $this->getDoctrine()->getManager();
        $em->persist($bill);
        $em->flush();

        return  $bill;
    }

    /**
     * @return int
     * 获得用户账单数量
     */
    public function getBillsNumber()
    {
        $categories = $this->getDoctrine()->getRepository("AccountBundle:Category")->loadByUser($this->getUser());
        $number = $this->getDoctrine()->getRepository("AccountBundle:Bill")->loadCountByCategory($categories);
        return $number ? $number : 0;
    }

    /**
     * @param $page
     * @param $limit
     * @return array
     * 获取用户账单
     */
    public function getBills($page, $limit)
    {
        $number = $this->getBillsNumber();

        if($number == 0)
        {
            return [
                'page'      => 1,
                'total'     => $number,
                'max_page'  => 1,
                'total'     => 1,
                'number'    => 0,
                'bills'      => []
            ];
        }

        $max_page = ceil($number / $limit);
        $page   =   $page < 1 ? 1 : $page;
        $page   =   $page > $max_page ? $max_page : $page;

        $categories = $this->getDoctrine()->getRepository("AccountBundle:Category")->loadByUser($this->getUser());

        /**
         * @var Bill[]
         */
        $bills      = $this->getDoctrine()->getRepository("AccountBundle:Bill")->loadByCategory($categories, $page, $limit);


        $data = [
            'page'      => $page,
            'max_page'  => $max_page,
            'total'     => $number,
            'count'    => count($bills)
        ];

        $bills_array = [];

        foreach ($bills as $bill) {
            $tmp = [];
            $tmp['id']  = $bill->getId();
            $tmp['what_for']    =   $bill->getWhatFor();
            $tmp['location']    =   $bill->getLocation();
            $tmp['address']     =   $bill->getAddress();
            $tmp['time']        =   $bill->getTime();
            $tmp['type']        =   [
                'id'            =>  $bill->getType()->getId(),
                'name'          =>  $bill->getType()->getName()
            ];
            $tmp['category']    =  [
                'id'            =>  $bill->getCategory()->getId(),
                'name'          =>  $bill->getCategory()->getName()
            ];

            $bills_array[]      =   $tmp;
        }

        $data['bills'] = $bills_array;

        return $data;
    }
}